﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ImageHandler;
using MS.Internal.Xml.XPath;
using Stamp_For_Africa_Version_2.Helpers;
using Stamp_For_Africa_Version_2.Models;
using Stamp_For_Africa_Version_2.Repositories;
using Stamp_For_Africa_Version_2.ViewModels;

namespace Stamp_For_Africa_Version_2.Controllers
{
    public class MyStampsController : Controller
    {
      private Guid GetUserId()
      {
        MembershipUser user = Membership.GetUser();
        Guid userId = Guid.Empty;
        if (user != null)
          userId = (Guid)user.ProviderUserKey;

        return userId;
      }

      private void BuildViewBagItems(List<SelectListItem> countryList, List<SelectListItem> categoryItems, List<SelectListItem> firstIssueDates , List<SelectListItem> subCategoryItems   )
      {
        
        List<SelectListItem> issueType = new List<SelectListItem>();
        SelectListItem regularIssue = new SelectListItem
        {
          Text = "Regular (Definitive) Issue",
          Value = "0"
        };
        SelectListItem provisionalIssue = new SelectListItem
        {
          Text = "Provisional Issue",
          Value = "1"
        };
        SelectListItem commemorativeIssue = new SelectListItem
        {
          Text = "Commemorative Issue",
          Value = "2"
        };
        issueType.Add(regularIssue);
        issueType.Add(provisionalIssue);
        issueType.Add(commemorativeIssue);

        ViewBag.CountryList = countryList;
        ViewBag.CategoryList = categoryItems;
        ViewBag.IssueTypeList = issueType;
        ViewBag.FirstIssueList = firstIssueDates;
        ViewBag.SubCategoryList = subCategoryItems;
      }

        //
        // GET: /MyStamps/
        [Authorize]
        public ActionResult Index()
        {
          StampRepository stampRepository = new StampRepository();
          CollectionRepository collectionRepository = new CollectionRepository();
          CountryRepository countryRepository = new CountryRepository();
          CategoryRepository categoryRepository = new CategoryRepository();

          MyStampCollectionViewModel collectionViewModel = new MyStampCollectionViewModel();
					IQueryable<Collection> myCollection = collectionRepository.GetMyCollection(GetUserId());
          List<Country> listOfCountries = new List<Country>();
          List<Category> listOfCategoris = new List<Category>();
          List<String> listOfSubCategories = new List<string>();
          List<String> listOfFirstIssueDates = new List<string>();
          int totalMintStamps = 0;
          int totalMintHingedStamps = 0;
          int totalUsed = 0;
          int total = 0;
          foreach (var collection in myCollection)
          {
            switch (collection.State)
            {
							case Collection.StampState.MintNeverHinged:
                totalMintStamps += collection.Quantity;
                break;
							case Collection.StampState.MintHinged:
                totalMintHingedStamps += collection.Quantity;
                break;
							case Collection.StampState.Used:
                totalUsed += collection.Quantity;
                break;
            }

            Country country = countryRepository.GetCountry(stampRepository.GetStamp(collection.StampId, Guid.Empty).CountryId);
            Category category =
              categoryRepository.GetCategory(stampRepository.GetStamp(collection.StampId, Guid.Empty).CategoryId);
            String subCategory = stampRepository.GetStamp(collection.StampId, Guid.Empty).SubCategory;
            String firstIssue = stampRepository.GetStamp(collection.StampId, Guid.Empty).ToString();

            if (!listOfCountries.Contains(country))
              listOfCountries.Add(country);

            if (!listOfCategoris.Contains(category))
              listOfCategoris.Add(category);

            if (!listOfSubCategories.Contains(subCategory))
              listOfSubCategories.Add(subCategory);

            if (!listOfFirstIssueDates.Contains(firstIssue))
              listOfFirstIssueDates.Add(firstIssue);
            
          }
          collectionViewModel.TotalNumberOfStamps = totalMintHingedStamps + totalMintStamps + totalUsed;
          collectionViewModel.TotalNumberOfMintNeverHingedStamps = totalMintStamps;
          collectionViewModel.TotalNumberOfMintHingedStamps = totalMintHingedStamps;
          collectionViewModel.TotalNumberOfUsedStamps = totalUsed;
          collectionViewModel.TotalNumberOfCountries = listOfCountries.Count;
          collectionViewModel.ListOfCountries = listOfCountries;
          ViewBag.StampCollectionViewModel = collectionViewModel;
          
          StampIndexFormViewModel stampIndexFormViewModel = new StampIndexFormViewModel();
          ViewBag.StampIndexFormViewModel = stampIndexFormViewModel;
          BuildViewBagItems(listOfCountries.Select(c => new SelectListItem {Value = c.Id.ToString(), Text = c.Name }).ToList(), 
                            listOfCategoris.Select(c => new SelectListItem {Value = c.Id.ToString(), Text = c.DisplayName }).ToList(),
                            listOfFirstIssueDates.Select(c => new SelectListItem {Value = c, Text = c }).ToList(),
                            listOfSubCategories.Select(c => new SelectListItem { Value = c, Text = c }).ToList());

          return View();
        }

        [Authorize]
        public ActionResult DoSearch(FormCollection formCollection)
        {
          String imagePath = formCollection["UserUploadedFileForSearch"];
          String sMaxResults = formCollection["MaxResults"];
          String serverPath = formCollection["NonRootedFileForSearch"];
          String SearchCategoryId = formCollection["SearchCategoryId"];
          String SearchCountryId = formCollection["SearchCountryId"];
          String SearchCurrencyId = formCollection["SearchCurrencyId"];
          String SearchText = formCollection["SearchText"];


          if (!String.IsNullOrEmpty(imagePath))
          {
            return DoImageSearch(imagePath, sMaxResults, serverPath, SearchCategoryId, SearchCountryId, SearchText);
          }
          else
          {
            return TextSearch(sMaxResults, SearchCategoryId, SearchCountryId, SearchText);
          }




        }


        public ActionResult TextSearch(String sMaxResults, String SearchCategoryId, String SearchCountryId, String SearchText)
        {

          if (String.IsNullOrEmpty(SearchText))
            return RedirectToAction("Index");

          TextSearcher searcher = new TextSearcher();
          searcher.BuildTextSearcher(SearchText);
          searcher.RunTextSearch();

          if (String.IsNullOrEmpty(sMaxResults))
            sMaxResults = "10";

          SearchFormViewModel searchFormViewModel = new SearchFormViewModel();
          searchFormViewModel.SearchResults = searcher.HitList.Select(u => u.Stamp);
          searchFormViewModel.SearchedWithImage = false;
          return View("SearchResults", searchFormViewModel);


          //List<Stamp> countries = _stampRepository.FindAllStamps()

          /*
          Guid countryGuid = Guid.Empty;
          Guid categoryGuid = Guid.Empty;
          if (!String.IsNullOrEmpty(SearchCountryId))
            countryGuid = Guid.Parse(SearchCountryId);
          if (!String.IsNullOrEmpty(SearchCategoryId))
            categoryGuid = Guid.Parse(SearchCategoryId);

          IQueryable<Stamp> results = _stampRepository.FindAllStamps(Guid.Empty);
          if (countryGuid != Guid.Empty)
          {
            results = results.Where(u => u.CountryId == countryGuid);
          }
          if (categoryGuid != Guid.Empty)
          {
            results = results.Where(u => u.CategoryId == categoryGuid);
          }

          //Text search
          */
          /*
          StampIndexFormViewModel formViewModel = null;
          if (TempData.ContainsKey("FormFilters"))
          {
            formViewModel = (StampIndexFormViewModel)TempData["FormFilters"];
            TempData["FormFilters"] = formViewModel;
          }
          else
          {
            formViewModel = new StampIndexFormViewModel();
            formViewModel.StampList = _stampRepository.SearchRange(0, 4, SearchText, "", "", "", GetUserId());
          }

          BuildViewBagItems();
          */


        }

        public ActionResult DoImageSearch(String imagePath, String sMaxResults, String serverPath, String SearchCategoryId, String SearchCountryId,
          String SearchText)
        {

          if (String.IsNullOrEmpty(sMaxResults))
            sMaxResults = "10";

          MatchResults matchResults = new MatchResults();
          //matchResults.MaxResults = 10;

          if (!String.IsNullOrEmpty(imagePath))
          {
            matchResults = Helpers.ImageSearcher.FindBestImagesMatches(imagePath, int.Parse(sMaxResults));
            if (TempData["SearchResults"] != null)
              TempData.Remove("SearchResults");
            TempData.Add("SearchResults", matchResults);
            if (TempData["SearchedImage"] != null)
              TempData.Remove("SearchedImage");
            if (TempData["UserServerImagePath"] != null)
              TempData.Remove("UserServerImagePath");

            TempData.Add("SearchedImage", imagePath);
            TempData.Add("UserServerImagePath", serverPath);
          }
          return RedirectToAction("SearchResults", "MyStamps");
        }

        public ActionResult SearchResults()
        {
          MatchResults matchResults = null;
          StampRepository repository = new StampRepository();
          String searchedImage = "";
          String searchedImageServerPath = "";
          if (TempData["SearchResults"] != null)
          {
            matchResults = (MatchResults)TempData["SearchResults"];
          }
          if (TempData["SearchedImage"] != null)
          {
            searchedImage = (string)TempData["SearchedImage"];
          }
          if (TempData["UserServerImagePath"] != null)
            searchedImageServerPath = (string)TempData["UserServerImagePath"];

          SearchFormViewModel searchFormViewModel = new SearchFormViewModel();
          searchFormViewModel.SearchResults = repository.FindAllStamps(matchResults);
          searchFormViewModel.SearchedWithImage = true;
          searchFormViewModel.ImageSearchedFor = searchedImage;
          searchFormViewModel.NonRootedImageSearchedFor = searchedImageServerPath;
          return View(searchFormViewModel);


        }













    }
}
